<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\UserAction\RestorePasswordChance;
use App\Models\User;
use App\Models\GcGroup;
use App\Models\GcCategory;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Jobs\StormSmsJob;
use Encore\Admin\Layout\Content;
use App\Admin\Tools\UserBatchSmsTool;
use App\Admin\Actions\UserAction\Orders;
use App\Admin\Actions\UserAction\Upgrades;
use App\Admin\Actions\UserAction\TeamOnes;
use App\Admin\Actions\UserAction\TeamTwos;
use App\Admin\Actions\UserAction\VipPurchase;
use App\Admin\Actions\UserAction\DismissMelt;
use App\Admin\Actions\UserAction\UserBalance;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\UserAction\UserGoldBeans;
use App\Admin\Actions\UserAction\SyncUserCache;
use App\Admin\Actions\UserAction\UserGoldCoins;
use App\Admin\Actions\UserAction\DismissPayCode;
use App\Admin\Actions\UserAction\SyncStormCache;
use App\Admin\Actions\UserAction\UserGoldRecords;
use App\Admin\Actions\UserAction\AdminUserBind;
use App\Admin\Actions\UserAction\AdminUserBindDismiss;
use App\Admin\Actions\UserAction\TransferGoldCoins;
use App\Admin\Actions\UserAction\TransferGoldBeans;
use App\Admin\Actions\UserAction\TransferBalance;
use App\Admin\Actions\UserAction\AlipayBindDismiss;
use App\Admin\Actions\UserAction\WechatBindDismiss;
use App\Admin\Actions\UserAction\TransferGoldCashes;
use App\Admin\Actions\UserAction\BankCardBindDismiss;
use App\Admin\Actions\UserAction\TransferGoldSubsidies;
use Encore\Admin\Facades\Admin;

abstract class CommonUsersController extends AdminController
{
    protected $title = '会员列表';

    abstract protected function getType();
    abstract protected function customedGrid(Grid $grid);
    abstract protected function customedDetail($id);
    abstract protected function customedForm(Form $form);

    protected function getTeam(Grid $grid)
    {
	    if (request('level') == 1 and $userId = request('user_id')) {
		    $grid->model()->where('parent_id', $userId)->orderByDesc('id');
	    }
	    if (request('level') == 2 and $userId = request('user_id')) {
	    	$user = User::query()->find($userId);
		    $grid->model()->whereIn('parent_id', $user->myDownOneChildren()->pluck('id'))->orderByDesc('id');
	    }
    }

    protected function grid()
    {
        $grid = new Grid(new User());

   		if($this->getType()=="myUser"){

   			$roleId = Admin::user()->isAdministrator();
	    	if($roleId){

				$grid->model()->orderByDesc('id');
	    	}else{

	    		$grid->model()->where("admin_user_id",Admin::user()->id)->orderByDesc('id');
	    	}

   		}else{

   			$grid->model()->orderByDesc('id');
   		}
	    

	    $this->getTeam($grid);

	    $grid->column('name', '会员')->display(function () {
		    return $this->nameText(true);
	    });
       /* $grid->column('admin_user_id', '绑定小二')->display(function () {
        	 return $this->admin_user_id ? _true() : _false();
        });*/
        
        $grid->column('invite_code', '邀请码')->copyable();
        $grid->column('phone', '手机');

        $grid->column('gc_group_id', '当前分组')->display(function () {
        	return $this->gcgroup ? $this->gcgroup->name : ''; 
        });

         $grid->column('gc_old_group_id', '最初分组')->display(function () {
        	return $this->gcOldGroup ? $this->gcOldGroup->name : '';
        });

        $grid->column('gc_cateory_id', '账号分类')->display(function () {
        	return $this->gcCategory ? $this->gcCategory->name : ''; 
        });

        $grid->column('xhs_num', '小红书账号数');
        $grid->column('dy_num', '抖音账号数');
        $grid->column('sph_num', '视频号账号数');
        $grid->column('ks_num', '快手账号数');
        $grid->column('fyb_num', '副业帮账号数');
        $grid->column('xhs_fans', '小红书粉丝数');
        $grid->column('dy_fans', '抖音粉丝数');
        $grid->column('sph_fans', '视频号粉丝数');
        $grid->column('ks_fans', '快手粉丝数');
        $grid->column('fyb_fans', '副业帮粉丝数');
       	
       	 $grid->column('is_stop', '是否停止推送图文')->display(function () {
        	return $this->stopText(true);
        });
       
	    $grid->column('created_at', '创建时间')->display(function () {
		    return (string)$this->created_at;
	    });
        

        

        

        $grid->disableRowSelector();
        $grid->disableExport();

        $this->gridTools($grid);
        $this->gridFilter($grid);
        $this->gridActions($grid);

        $this->customedGrid($grid);

        return $grid;
    }

    protected function gridTools(Grid $grid)
    {
	    $grid->tools(function (Grid\Tools $tools) {
	    	$tools->append(new UserBatchSmsTool());
	    });
    }

    protected function gridFilter(Grid $grid)
    {
    	$grid->filter(function (Grid\Filter $filter) {

    		$filter->expand();

		    $filter->scope('normal', '未停产用户')->where('is_stop', false);
		  

    		$filter->column(1/2, function (Grid\Filter $filter) {
    			$filter->disableIdFilter();
    			$filter->equal('id', 'ID 查询');
			    $filter->like('name', '昵称查询');
			    $filter->equal('gc_category_id', '分类查询')->select(GcCategory::get()->pluck('name', 'id'));
		    });

    		$filter->column(1/2, function (Grid\Filter $filter) {
			    $filter->equal('invite_code', '邀请码');
			    $filter->endsWith('phone', '手机号');
		    });

		    
	    });
    }

    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableDelete();

	    	/*if (in_array(Admin::user()->id, [1,3,27,37])) {
				$actions->add(new TransferGoldCoins());
			}
	    	
	    	$actions->add(new TransferGoldBeans());
	    	$actions->add(new TransferGoldCashes());
	    	$actions->add(new TransferBalance());
		   
		    $actions->add(new Orders());
		    $actions->add(new TeamOnes());
		    $actions->add(new TeamTwos());
		    $actions->add(new RestorePasswordChance());
		    $actions->add(new AlipayBindDismiss());
		    $actions->add(new BankCardBindDismiss());
 			$actions->add(new AdminUserBind());
 			$actions->add(new AdminUserBindDismiss());*/

 			
		    
	    });
    }

    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->field('id', 'ID');
        $show->field('parent_id', '上级');
        $show->field('grade', '等级');
        $show->field('phone', '手机');
        $show->field('name', '昵称');
        $show->field('avatar', '头像');
        $show->field('sex', '性别');
        $show->field('birth', '生日');
        $show->field('wx_openid', __('Wx openid'));
        $show->field('wx_nickname', __('Wx nickname'));
        $show->field('wx_headimgurl', __('Wx headimgurl'));
        $show->field('wx_province', __('Wx province'));
        $show->field('wx_city', __('Wx city'));
        $show->field('invite_code', '邀请码');
        $show->field('is_locked', '锁定状态');
        $show->field('is_parent', '有下级');
        $show->field('created_at', '创建时间');
        $show->field('updated_at', '修改时间');
         $show->field('vip_expired_at', '会员到期时间');

        $show->panel()->tools(function (Show\Tools $tools) {
        	$tools->disableDelete();
        });

        $this->customedDetail($id);

        return $show;
    }

    public function smsForm(Content $content)
    {
	    // return $content->header('批量发送金店活动短信')
		   //  ->body(view('admin.users.batchsms'));
    }

    public function smsStore()
    {
    	$state = request('state');
	    $phones = request('phones');
	    $phones = collect(explode("\r\n", $phones));

	    if (!in_array($state, [0,1])) {
		    admin_toastr('仅可发送金店活动短信', 'error');
		    return redirect()->back();
	    }
	    if (empty($phones->first())) {
		    admin_toastr('请输入手机号码', 'error');
		    return redirect()->back();
	    }
	    if ($phones->count() > 500) {
		    admin_toastr('不可超过500条短信/次', 'error');
		    return redirect()->back();
	    }

	    $isSuccess = $state == 1 ? true : false;

	    foreach ($phones as $phone) {

	    	$phone = trim($phone);

	    	if (empty($phone)) continue;

		    if(preg_match("/^1[3456789]\d{9}$/", $phone)){
			    dispatch(new StormSmsJob($phone, $isSuccess));
		    }
	    }

	    admin_toastr('提交成功', 'success');
	    return redirect()->back();
    }

    protected function form()
    {
        $form = new Form(new User());

        //$this->customedForm($form);

        $form->divider('用户信息操作');
        $form->text('name', '用户名称')->rules('required');
        $form->text('phone', '用户手机号')->rules('required');
        $form->select('gc_group_id', '分组')->options(GcGroup::get()->pluck('name', 'id'))->rules('required');
        $form->select('gc_category_id', '分类')->options(GcCategory::get()->pluck('name', 'id'))->rules('required');
	    $form->number('xhs_num', '小红书账号数');
	    $form->number('dy_num', '抖音账号数');
	    $form->number('sph_num', '视频号账号数');
	    $form->number('ks_num', '快手账号数');
	    $form->number('fyb_num', '副业帮账号数');
	    $form->switch('is_stop', '停止');

        $this->formTools($form);
        $this->formSaving($form);

        return $form;
    }

    protected function formTools(Form $form)
    {
    	$form->tools(function (Form\Tools $tools) {
		    $tools->disableDelete();
	    });
    }

    protected function formSaving(Form $form)
    {
    	$form->saving(function (Form $form) {
		    // Passowrd for editing mode
    		if (!empty($form->phone)) {
		    	$exists = User::query()->where('phone',$form->phone)->where('id','!=',$form->model()->id)->exists();
		    	
		    	if($exists){

		    	   admin_toastr('该用户已存在', 'error');
             	   return redirect('/admin/users');
		    	}
		    }
    		// Password for creating mode
		  
	    	/*if(empty($form->password)){
	    		$password = substr($form->phone,-6);
	    		
	    		$form->password = bcrypt($password);
	    		dd($form);
	    	}
	    	*/
		    


	    });
    }
}
